﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Basic.Redis.Providers.StackExchange;

public partial class DefaultRedisProvider
{
    /// <summary>
    /// 分布式锁
    /// </summary>
    /// <param name="key"></param>
    /// <param name="timeout">默认60s</param>
    /// <returns></returns>
    public bool LockTake(string key, string value, TimeSpan? timeout = null)
    {
        if (timeout == null)
            timeout = TimeSpan.FromSeconds(60);
        return _redisDb.LockTake(key, value, timeout.Value);
    }

    /// <summary>
    /// 分布式锁
    /// </summary>
    /// <param name="key"></param>
    /// <param name="timeout">默认60s</param>
    /// <returns></returns>
    public Task<bool> LockTakeAsync(string key, string value, TimeSpan? timeout = null)
    {
        if (timeout == null)
            timeout = TimeSpan.FromSeconds(60);
        return _redisDb.LockTakeAsync(key, value, timeout.Value);
    }

    /// <summary>
    /// 释放锁
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool LockRelease(string key, string value) => _redisDb.LockRelease(key, value);

    /// <summary>
    /// 释放锁
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public Task<bool> LockReleaseAsync(string key, string value) => _redisDb.LockReleaseAsync(key, value);

    /// <summary>
    /// 查询锁
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public string LockQuery(string key) => _redisDb.LockQuery(key).ToString();

    /// <summary>
    /// 查询锁
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public async Task<string> LockQueryAsync(string key)
    {
        return (await _redisDb.LockQueryAsync(key)).ToString();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="timeout"></param>
    /// <returns></returns>
    public bool LockExtend(string key, string value, TimeSpan? timeout = null)
    {
        if (timeout == null)
            timeout = TimeSpan.FromSeconds(60);
        return _redisDb.LockExtend(key, value, timeout.Value);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="timeout"></param>
    /// <returns></returns>
    public Task<bool> LockExtendAsync(string key, string value, TimeSpan? timeout = null)
    {
        if (timeout == null)
            timeout = TimeSpan.FromSeconds(60);
        return _redisDb.LockExtendAsync(key, value, timeout.Value);
    }

}